package net.caidingke.shepherd.controller.base;

import lombok.extern.slf4j.Slf4j;
import net.caidingke.shepherd.utils.result.Result;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import net.caidingke.shepherd.exception.BusinessException;
import net.caidingke.shepherd.exception.ErrorCode;

import static net.caidingke.shepherd.utils.result.ResultGenerator.error;

/**
 * @author bowen
 */
@RestControllerAdvice
@Slf4j
public class GlobalDefaultExceptionHandler {

    private static final Result<String> SERVER_ERROR =
            error(ErrorCode.ERROR.getCode(), ErrorCode.ERROR.getMsg());

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BusinessException.class)
    public Result handlerBusinessException(BusinessException exception) {
        log.error(exception.getMsg(), exception);
        return error(exception.getCode(), exception.getMsg());
    }

    // @ResponseStatus(HttpStatus.UNAUTHORIZED)
    // @ExceptionHandler({AuthenticationException.class, UnknownAccountException.class,
    //        UnauthenticatedException.class, IncorrectCredentialsException.class,
    //        UnauthorizedException.class})
    // public void handlerUnauthorizedException(Exception exception) {
    //    log.warn(exception.getMessage(), exception);
    // }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Result handlerException(Exception exception) {
        log.error(exception.getMessage(), exception);
        return SERVER_ERROR;
    }
}
